import org.jsecurity.SecurityUtils

class AccountController extends BaseController {
	
	CryptoService cryptoService
	
	def index = { redirect(action:'show',params:params)
	}
	
	def show = {
		if(!session.account) {
			flash.message = "Account not found"
			redirect(action:'signup')
			return
		}	
		
		def account = Account.get( session.account.id );
		
		if(!account) {
			flash.message = "Account not found with username ${subject.principal}"
			redirect(action:'signup')
			return
		} else {
			render(view:'show',model:[account:account])
			return
		}
	}
	
	def signup = {
		def account = new Account()
		account.properties = params
		return ['account':account]
	}
	
	def register = {
		// The register action is not added to the security filter
		// to allow submitting the sign-up form (workaround)
		if (!params.username || !params.password) {
			flash.message = "Username or password empty!"
			render(view:'signup')
			return
		}
		
		def account = new Account()
		account.properties = params
		
		def user = new User()
		user.properties = params
		
		def role = Role.USER
		role.save()
		
		account.role = role
		account.password = cryptoService.encrypt(params.password.getBytes())
		account.user = user
		
		if(account.save()) {
			flash.message = "Account ${account.username} created."
			redirect(controller: 'login', action: 'login', params: params)
			return
		} else {
			flash.message = "Error creating account."
			account.password = params.password
			render(view:'signup', model:[account:account])
			return
		}
	}
	
}